package biz.datalk.industrialland.common.log.task;

import biz.datalk.commons.utils.BasicParserUtils;
import biz.datalk.industrialland.common.log.mapper.ISysLogExtMapper;
import biz.datalk.industrialland.common.log.mapper.ISysLogMapper;
import biz.datalk.industrialland.common.log.pojo.bo.LogBO;
import biz.datalk.industrialland.common.log.pojo.po.SysLog;
import biz.datalk.industrialland.common.log.pojo.po.SysLogExt;
import biz.datalk.industrialland.common.log.util.SysLogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

/**
 * @author tarofang@163.com
 * @date 2020-11-24
 */
public class SysLogSaveMySQL implements SysLogSaveRunnable {
    private static final Logger log = LoggerFactory.getLogger(SysLogSaveMySQL.class);

    private final ISysLogMapper sysLogMapper;
    private final ISysLogExtMapper sysLogExtMapper;
    private final String serverPrivateKey;
    private final LogBO logBO;
    private final boolean needDecryptReqBodyParam;

    public SysLogSaveMySQL(ISysLogMapper sysLogMapper, ISysLogExtMapper sysLogExtMapper, //
                           String serverPrivateKey, LogBO logBO, boolean needDecryptReqBodyParam) {
        this.sysLogMapper = sysLogMapper;
        this.sysLogExtMapper = sysLogExtMapper;
        this.serverPrivateKey = serverPrivateKey;
        this.logBO = logBO;
        this.needDecryptReqBodyParam = needDecryptReqBodyParam;
    }

    @Override
    public void run() {
        boolean isDebug = log.isDebugEnabled();
        if (isDebug) {
            log.debug("SysLogSaveMySQL.run() ============================== into");
        }
        try {
            if (this.needDecryptReqBodyParam) {
                String decryptReqBody = SysLogUtil.decryptReqBody(this.logBO.getReqBodyParam(), this.serverPrivateKey);
                this.logBO.setReqBodyPlaintext(decryptReqBody);
            }

            // if (ModuleEnum.OPEN.getModuleCode().equals(this.logBO.getOptModuleCode()) //
            //         && StringUtils.isNotBlank(this.logBO.getOpenReqResultData())) {
            //     this.logBO.setReqResult(this.logBO.getOpenReqResultData());
            // }

            SysLog sysLog = new SysLog();
            BeanUtils.copyProperties(this.logBO, sysLog);
            sysLog.setOptUserId(BasicParserUtils.parseLong(this.logBO.getOptUserId(), -1L));
            sysLogMapper.insertSelective(sysLog);

            SysLogExt sysLogExt = new SysLogExt();
            BeanUtils.copyProperties(this.logBO, sysLogExt);
            sysLogExt.setSysLogId(sysLog.getId());
            sysLogExtMapper.insertSelective(sysLogExt);
        } finally {
            if (isDebug) {
                log.debug("SysLogSaveMySQL.run() ============================== out");
            }
        }
    }
}
